package com.zhida.userservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.zhida.common.context.UserContext;
import com.zhida.common.entity.Result;
import com.zhida.common.utils.ObjectUtil;
import com.zhida.common.utils.SaltMD5Util;
import com.zhida.common.utils.TokenProcessor;
import com.zhida.userservice.entity.User;
import com.zhida.userservice.entity.UserInfo;
import com.zhida.userservice.mapper.UserInfoMapper;
import com.zhida.userservice.mapper.UserMapper;
import com.zhida.userservice.service.IUserService;
import jakarta.annotation.Resource;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.zhida.common.utils.RegexUtil.TOKEN_EXPIRE_TIME;
import static com.zhida.common.utils.RegexUtil.TOKEN_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Your Name
 * @since 2024-07-15
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    UserMapper userMapper;
    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    RedisTemplate<String,Object> redisTemplate;

    @Override
    public Result<?> login(User user){
//        将user的password字段进行加密
        user.setPassword(SaltMD5Util.generateSaltPassword(user.getPassword()));
//        从数据库中查询是否存在这一条数据
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        根据用户名和密码查找用户id
        queryWrapper.allEq(Map.of("password",user.getPassword(),"username",user.getUsername()));
        User result = userMapper.selectOne(queryWrapper);
        if (result!=null){
            String token = TokenProcessor.createToken(user.getUsername());
//            获取用户的账户信息
            HashMap<String,String> userInfo = userMapper.getUserInfo(user.getUsername());
            userInfo.put("token",token);
            //  将登陆信息存入redis并设置7天过期
            try {
                redisTemplate.opsForValue().set(TOKEN_KEY + user.getUsername(), ObjectUtil.Object2JsonStr(userInfo), TOKEN_EXPIRE_TIME , TimeUnit.DAYS );
            }catch (JsonProcessingException e){
                e.printStackTrace();
            }
            return Result.success(Map.of("token",token,"username",user.getUsername()));
        }
        System.out.println(user.getPassword());
        return Result.error("密码错误");
    }

    @Override
    public Result<?> register(User user) {
//        判断用户是否存在
        User result = userMapper.selectOne(new QueryWrapper<User>().eq("username",user.getUsername()));
        if (result!=null){
            return Result.error("用户已存在");
        }
//        插入一条 用户信息
        user.setPassword(SaltMD5Util.generateSaltPassword(user.getPassword()));
        userMapper.insert(user);
//        查询当前用户的user_id
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(user.getUsername());
        userInfoMapper.insert(userInfo);
        System.out.println(userInfo);
        return Result.successMsg("注册成功");
    }

    @Override
    public Result<?> updateUserInfo(User user) {
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        if (StringUtils.isNotBlank(user.getNickname())){
            userUpdateWrapper.set("nickname",user.getNickname());
        }
        if (StringUtils.isNotBlank(user.getHeader())){
            userUpdateWrapper.set("header",user.getHeader());
        }
        if (StringUtils.isNotBlank(user.getEmail())){
            userUpdateWrapper.set("email",user.getEmail());
        }
        if (StringUtils.isNotBlank(user.getPhone())){
            userUpdateWrapper.set("phone",user.getPhone());
        }
        userUpdateWrapper.eq("username",UserContext.getUser());
        int update_flag = userMapper.update(userUpdateWrapper);
        if (update_flag == 0){
            return Result.error("用户信息更新失败");
        } else {
            return Result.successMsg("更新成功");
        }
    }

    @Override
    public Result<?> getUserInfo() throws JsonProcessingException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("username", UserContext.getUser());
        queryWrapper.select("username","vip_status","create_time","header","financial","emotional","skill","nickname","email","phone");
        Map<String, Object> userMap = userMapper.selectMaps(queryWrapper).get(0);
        return Result.success(userMap);
    }
}
